﻿import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import re

def mod49(num, step):
    """数值计算修正版"""
    return (num + step - 1) % 49 + 1

class LotteryPredictor:
    def __init__(self, root):
        self.root = root
        self.root.title("彩票智能预测器 v3.3")
        self.root.geometry("1200x800")
        self.setup_ui()

    def setup_ui(self):
        """界面布局"""
        # 输入区
        input_frame = ttk.LabelFrame(self.root, text="输入区（最新一期在最上面，每行7个数字）")
        input_frame.pack(padx=20, pady=10, fill=tk.BOTH, expand=True)
        
        self.text_input = scrolledtext.ScrolledText(
            input_frame,
            wrap=tk.WORD,
            width=120,
            height=15,
            font=('Consolas', 10),
            background="#FFFFE0"
        )
        self.text_input.pack(fill=tk.BOTH, expand=True)
        
        # 示例数据
        example = "示例输入（最新一期在最上面）：\n"
        example += "13 6 12 18 33 49 2\n"
        example += "43 13 35 7 12 33 18\n"
        example += "（至少需要两期数据）"
        self.text_input.insert(tk.END, example)

        # 控制按钮
        control_frame = ttk.Frame(self.root)
        control_frame.pack(pady=10)
        
        style = ttk.Style()
        style.configure("Action.TButton", font=('微软雅黑', 10), padding=6)
        
        ttk.Button(control_frame, text="立即分析", command=self.perform_analysis, style="Action.TButton").pack(side=tk.LEFT, padx=5)
        ttk.Button(control_frame, text="清空数据", command=self.clear_data, style="Action.TButton").pack(side=tk.LEFT, padx=5)
        ttk.Button(control_frame, text="导出结果", command=self.export_results, style="Action.TButton").pack(side=tk.LEFT, padx=5)

        # 结果区
        result_frame = ttk.LabelFrame(self.root, text="预测结果")
        result_frame.pack(padx=20, pady=10, fill=tk.BOTH, expand=True)
        
        self.result_tree = ttk.Treeview(
            result_frame, 
            columns=("steps", "prediction"), 
            show="headings",
            height=20,
            selectmode="extended"
        )
        
        # 列配置
        columns = [
            ("steps", "步长序列", 400),
            ("prediction", "预测号码（可直接复制）", 750)
        ]
        for col_id, col_text, width in columns:
            self.result_tree.heading(col_id, text=col_text, anchor=tk.W)
            self.result_tree.column(col_id, width=width, anchor=tk.W)

        # 滚动条和布局
        vsb = ttk.Scrollbar(result_frame, orient="vertical", command=self.result_tree.yview)
        hsb = ttk.Scrollbar(result_frame, orient="horizontal", command=self.result_tree.xview)
        self.result_tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        self.result_tree.grid(row=0, column=0, sticky="nsew")
        vsb.grid(row=0, column=1, sticky="ns")
        hsb.grid(row=1, column=0, sticky="ew")

        # 右键菜单
        self.context_menu = tk.Menu(self.root, tearoff=0)
        self.context_menu.add_command(label="复制号码", command=self.copy_numbers)
        self.result_tree.bind("<Button-3>", self.show_context_menu)

    def show_context_menu(self, event):
        """显示右键菜单"""
        self.context_menu.tk_popup(event.x_root, event.y_root)

    def copy_numbers(self):
        """直接复制预测号码"""
        selected = self.result_tree.selection()
        if not selected:
            return
        
        numbers = []
        for item in selected:
            prediction = self.result_tree.item(item, "values")[1]
            numbers.append(prediction)
        
        self.root.clipboard_clear()
        self.root.clipboard_append("\n".join(numbers))
        messagebox.showinfo("复制成功", f"已复制{len(numbers)}条号码到剪贴板")

    def generate_prediction(self, pattern, latest_numbers):
        """生成可直接复制的号码序列"""
        next_step = self.calculate_next_step(pattern)
        if next_step is None:
            return ""
        
        results = [str(mod49(num, next_step)) for num in latest_numbers]
        return " ".join(results)

    # 以下保持不变的方法（perform_analysis, calculate_next_step, validate_pattern等）
    def perform_analysis(self):
        """执行分析预测"""
        self.result_tree.delete(*self.result_tree.get_children())
        data, error = self.parse_input()
        if error:
            messagebox.showerror("输入错误", error)
            return
        
        latest_period = data[0] if data else []
        reversed_data = list(reversed(data))
        
        step_count = len(reversed_data) - 1
        patterns = self.generate_patterns(step_count)
        
        valid_sequences = []
        for pattern in patterns:
            if self.validate_pattern(reversed_data, pattern):
                prediction = self.generate_prediction(pattern, latest_period)
                if prediction:  # 过滤无效结果
                    valid_sequences.append((str(pattern), prediction))
        
        for seq in valid_sequences:
            self.result_tree.insert("", "end", values=seq)

    def calculate_next_step(self, pattern):
        """计算下一个步长"""
        if len(pattern) < 2:
            return None
        
        diff = pattern[1] - pattern[0]
        for i in range(2, len(pattern)):
            if pattern[i] - pattern[i-1] != diff:
                return None
        return pattern[-1] + diff

    def validate_pattern(self, data, pattern):
        """验证步长模式"""
        current_idx = 0
        for step in pattern:
            if current_idx >= len(data)-1:
                return False
            
            found = False
            for num in data[current_idx]:
                target = mod49(num, step)
                if target in data[current_idx + 1]:
                    current_idx += 1
                    found = True
                    break
            if not found:
                return False
        return True

    def parse_input(self):
        """解析输入"""
        raw = self.text_input.get("1.0", tk.END).strip()
        if not raw:
            return None, "无输入数据"
            
        periods = []
        lines = [ln for ln in raw.split('\n') if ln.strip()]
        
        try:
            for line in lines:
                nums = []
                seen = set()
                for part in re.findall(r'\d+', line):
                    num = int(part)
                    if num < 1 or num > 49:
                        raise ValueError(f"非法数字: {num}")
                    if num in seen:
                        raise ValueError(f"重复数字: {num}")
                    seen.add(num)
                    nums.append(num)
                    
                if len(nums) != 7:
                    raise ValueError("必须包含7个数字")
                periods.append(nums)
                
            if len(periods) < 2:
                raise ValueError("至少需要两期数据")
                
            return periods, None
            
        except Exception as e:
            return None, str(e)

    def generate_patterns(self, step_count):
        """生成步长模式"""
        patterns = []
        # 正递增
        for s in range(1, 50 - step_count):
            patterns.append([s + i for i in range(step_count)])
        # 正递减
        for s in range(step_count, 50):
            patterns.append([s - i for i in range(step_count)])
        # 负递增
        for s in range(-1, -50 + step_count, -1):
            patterns.append([s - i for i in range(step_count)])
        # 负递减
        for s in range(-step_count, -50, -1):
            patterns.append([s + i for i in range(step_count)])
        return patterns

    def clear_data(self):
        """清空数据"""
        self.text_input.delete("1.0", tk.END)
        self.result_tree.delete(*self.result_tree.get_children())

    def export_results(self):
        """导出结果"""
        messagebox.showinfo("导出说明", "右键选择要导出的行 → 点击'复制号码'")

if __name__ == "__main__":
    root = tk.Tk()
    app = LotteryPredictor(root)
    root.mainloop()